package com.zzedu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzedu.common.cache.CacheNameContansts;
import com.zzedu.common.constant.UserConstants;
import com.zzedu.common.core.domain.Ztree;
import com.zzedu.common.core.domain.entity.SysDictData;
import com.zzedu.common.core.domain.entity.SysDictType;
import com.zzedu.common.core.service.ISysDictDataService;
import com.zzedu.common.core.service.ISysDictTypeService;
import com.zzedu.common.utils.DictUtils;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.system.mapper.SysDictTypeMapper;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 字典 业务层处理
 *
 * @author smarthome
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {
    @Autowired
    ISysDictDataService sysDictDataService;

    @Autowired
    DictUtils dictUtils;
    /**
     * 缓存名称
     */
    final String cacheName = CacheNameContansts.SYS_DICT;

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public IPage<SysDictType> selectDictTypeList(IPage<SysDictType> page, SysDictType dictType) {
        LambdaQueryWrapper<SysDictType> queryWrapper = Wrappers.lambdaQuery(SysDictType.class);
        queryWrapper.eq(StringUtils.isNotBlank(dictType.getStatus()), SysDictType::getStatus, dictType.getStatus());
        queryWrapper.like(StringUtils.isNotBlank(dictType.getDictType()), SysDictType::getDictType, dictType.getDictType());
        queryWrapper.like(StringUtils.isNotBlank(dictType.getDictName()), SysDictType::getDictName, dictType.getDictName());
        Map map = dictType.getParams();
        if (!MapUtils.isEmpty(map)) {
            if (map.containsKey("beginTime")) {
                queryWrapper.ge(SysDictType::getGmtCreate, MapUtils.getString(map, "beginTime"));
            }
            if (map.containsKey("endTime")) {
                queryWrapper.le(SysDictType::getGmtCreate, MapUtils.getString(map, "endTime"));
            }
        }
        queryWrapper.orderByDesc(SysDictType::getId);
        return this.page(page, queryWrapper);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return this.list();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        return dictUtils.getDictCache(dictType);
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    @Cacheable(value = cacheName, key = "'dict:id_'+#p0")
    public SysDictType selectDictTypeById(Long dictId) {
        return getById(dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    @Cacheable(value = cacheName, key = "'dict:type_'+#p0")
    public SysDictType selectDictTypeByType(String dictType) {
        LambdaQueryWrapper<SysDictType> queryWrapper = Wrappers.lambdaQuery(SysDictType.class);
        queryWrapper.eq(SysDictType::getDictType, dictType);
        queryWrapper.orderByDesc(SysDictType::getId);
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }

    /**
     * 批量删除字典类型
     *
     * @param ids 需要删除的数据
     * @return 结果
     */
    @Override
    @CacheEvict(cacheNames = {CacheNameContansts.SYS_DICT}, allEntries = true)
    public void deleteDictTypeByIds(List<Long> dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            sysDictDataService.remove(Wrappers.lambdaQuery(SysDictData.class).eq(SysDictData::getDictType, dictType.getDictType()));
            removeById(dictId);
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    @CacheEvict(cacheNames = {CacheNameContansts.SYS_DICT}, allEntries = true)
    public void clearDictCache() {

    }

    /**
     * 重置字典缓存数据
     */
    @Override
    @CacheEvict(cacheNames = {CacheNameContansts.SYS_DICT}, allEntries = true)
    public void resetDictCache() {

    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @CacheEvict(cacheNames = {CacheNameContansts.SYS_DICT}, allEntries = true)
    public int insertDictType(SysDictType dict) {
        int row = baseMapper.insert(dict);
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    @CacheEvict(cacheNames = {CacheNameContansts.SYS_DICT}, allEntries = true)
    public int updateDictType(SysDictType dict) {
        int row = baseMapper.updateById(dict);
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(SysDictType dict) {
        Long dictId = StringUtils.isNull(dict.getId()) ? -1L : dict.getId();
        LambdaQueryWrapper<SysDictType> queryWrapper = Wrappers.lambdaQuery(SysDictType.class);
        queryWrapper.eq(SysDictType::getDictType, dict.getDictType());
        queryWrapper.last("limit 1");
        SysDictType dictType = getOne(queryWrapper);
        if (StringUtils.isNotNull(dictType) && dictType.getId().longValue() != dictId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 查询字典类型树
     *
     * @param dictType 字典类型
     * @return 所有字典类型
     */
    @Override
    public List<Ztree> selectDictTree(SysDictType dictType) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDictType> dictList = this.list();
        for (SysDictType dict : dictList) {
            if (UserConstants.DICT_NORMAL.equals(dict.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(dict.getId());
                ztree.setName(transDictName(dict));
                ztree.setTitle(dict.getDictType());
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    @Override
    public List<SysDictData> getRoleCodeSysDictData(String dictType) {
        return null;
    }

    public String transDictName(SysDictType dictType) {
        StringBuffer sb = new StringBuffer();
        sb.append("(" + dictType.getDictName() + ")");
        sb.append("&nbsp;&nbsp;&nbsp;" + dictType.getDictType());
        return sb.toString();
    }

}
